<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;

class Paper extends Model
{
  use Notifiable;
  protected $table = 'papers';

  // 列表
  public static function getList($request)
  {
    $query = self::select('*');
    if (isset($request->lx) && $request->lx) {
      $query->where('lx', $request->lx);
    }
    if (isset($request->status) && $request->status) {
      $query->where('status', $request->status);
    } 
    if (isset($request->cateid) && $request->cateid) {
      $query->where('cateid', $request->cateid);
    }
    if (isset($request->keywords) && $request->keywords) {
      $query->where('title', 'like', '%' . $request->keywords . '%');
    }
    if (isset($request->isHot) && $request->isHot) {
      $query->where('is_hot', $request->isHot);
    }
    if (isset($request->sort) && $request->sort) {
      $query->orderBy($request->sort, $request->order);
    } else {
      $query->orderBy('id', 'desc');
    }
    $res = $query->paginate($request->size);
    return $res ? $res->toArray() : [];
  }

  // 随机取热门
  public static function getRandList($request)
  {
    $query = self::select('*');
    if (isset($request->lx) && $request->lx) {
      $query->where('lx', $request->lx);
    }
    if (isset($request->isHot) && $request->isHot) {
      $query->where('is_hot', $request->isHot);
    }
    if (isset($request->cateId) && $request->cateId) {
      $query->where('cateid', $request->cateid);
    }
    if (isset($request->status) && $request->status) {
      $query->where('status', $request->status);
    }
    $res = $query->inRandomOrder()->take($request->size)->get();
    return $res ? $res->toArray() : [];
  }

  // 详情
  public static function getInfo($id) {
    $res = self::select('*')->where('id', $id)->first();
    // 点赞、收藏信息
    $loveInfo = DB::table('loves')->select('status')->where('paperid', $id)->first();
    $collectInfo = DB::table('collects')->select('status')->where('paperid', $id)->first();
    $res->love_status = $loveInfo ? $loveInfo->status:2;
    $res->collect_status = $collectInfo ? $collectInfo->status:2;

    return $res ? $res->toArray() : [];
  }

  public function collect() {
    return $this->hasOne('App\Models\Collect', 'paperid');
  }
}
